package com.ylc.chat.dao;

import com.ylc.chat.util.JDBCUtil;
import com.ylc.chat.entity.Chatrecord;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ylc
 * @Description:聊天记录持久层
 */
public class ChatrecordDao {
    /**
     * 根据发送方与接收方ID获取聊天记录
     * @param sendUid
     * @param receiveuid
     * @return
     */
    public List<Chatrecord> getRecordByUid(int sendUid, int receiveuid) {
        Connection conn = null;
        PreparedStatement pstmt =  null;
        ResultSet rs = null;

        List<Chatrecord> list = new ArrayList<>();
        try {
            conn =  JDBCUtil.getConnection();
            String sql = "select * from chatrecord where senduid = ? and receiveuid = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,sendUid);
            pstmt.setInt(2, receiveuid);
            rs = pstmt.executeQuery();
            while(rs.next()){
                Chatrecord chatrecord = new Chatrecord();
                chatrecord.setTid(rs.getInt("tid"));
                chatrecord.setRecord(rs.getString("record"));
                chatrecord.setDate(rs.getDate("date"));
                chatrecord.setSenduid(rs.getInt("senduid"));
                chatrecord.setReceiveuid(rs.getInt("receiveuid"));
                chatrecord.setType(rs.getInt("type"));
                list.add(chatrecord);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(rs,pstmt,conn);
        }
        return list;
    }

    /**
     * 新增聊天记录
     * @param chatrecord
     * @return
     */
    public int addRecord(Chatrecord chatrecord) {
        Connection conn = null;
        PreparedStatement pstmt =  null;
        int res = 0;

        try {
            conn =  JDBCUtil.getConnection();
            String sql = "INSERT INTO chat.chatrecord (record, `date`, senduid, receiveuid, `type`) VALUES(?, ?, ?, ?, ?);";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,chatrecord.getRecord());
            Timestamp time = new Timestamp(chatrecord.getDate().getTime());
            pstmt.setTimestamp(2, time);
            pstmt.setInt(3,chatrecord.getSenduid());
            pstmt.setInt(4,chatrecord.getReceiveuid());
            pstmt.setInt(5,chatrecord.getType());
            res = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(pstmt,conn);
        }
        return res;
    }
}
